using System;
using System.Web.Hosting;
using System.Web.Mvc;
using Xmlt.ViewEngine;

namespace Xmlt.ViewEngine
{
    public class XmltViewFactory : VirtualPathProviderViewEngine
    {
        public XmltViewFactory(VirtualPathProvider virtualPathProvider)
        {
            if(virtualPathProvider != null)
            {
                VirtualPathProvider = virtualPathProvider;
            }

            MasterLocationFormats = new string[0];

            ViewLocationFormats = new[]
                                      {
                                        "~/Views/{1}/{0}.xslt",
                                        "~/Views/{1}/{0}.xmlt",
                                        "~/Views/{1}/{0}.xml",
                                        "~/Views/Shared/{0}.xslt",
                                        "~/Views/Shared/{0}.xmlt",
                                        "~/Views/Shared/{0}.xml"
                                      };

            PartialViewLocationFormats = ViewLocationFormats;

            AreaMasterLocationFormats = new string[0];
            
            AreaViewLocationFormats = new[]{
                                        "~/Areas/{2}/Views/{1}/{0}.xslt",
                                        "~/Areas/{2}/Views/{1}/{0}.xmlt",
                                        "~/Areas/{2}/Views/{1}/{0}.xml",
                                        "~/Areas/{2}/Views/Shared/{0}.xslt",
                                        "~/Areas/{2}/Views/Shared/{0}.xmlt",
                                        "~/Areas/{2}/Views/Shared/{0}.xml"
            };

            AreaPartialViewLocationFormats = AreaViewLocationFormats;

        }

        public XmltViewFactory() : this(null)
        {
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            return CreateView(controllerContext, partialPath, null);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {

            var viewTemplate = new XmltTemplate(VirtualPathProvider, viewPath);

            var view = new XmltView(viewTemplate, controllerContext.Controller.ViewData.Model, string.Empty,
                                    controllerContext.HttpContext);
            return view;
        }
    }
}